/** Copyright 2014, Ross Mahony. Some rights reserved. See COPYING. */
package controllers

import java.text.SimpleDateFormat

import play.api._
import play.api.mvc._
import play.api.data._
import play.api.data.Forms._
import play.api.db.slick._
import play.api.Play.current
import play.api.libs.json._
// you need this import to have combinators
import play.api.libs.functional.syntax._

import views._
import models._

/** [[play.api.mvc.Controller]] for the energy usage chart view. */
object EnergyUsages extends Controller {

  import scala.collection.mutable.ListBuffer

  val sdf = new SimpleDateFormat("yyyy")

 /**
  * Action to display the energy usage page.
  *
  * @param id Customer ID
  */
  def index(id: Long) = DBAction { implicit rs =>
    CustomerDAO.loadCustomer(Some(id)).map { customer =>
      Ok(html.usage.index(customer))
    }.getOrElse(NotFound)
  }

 /**
  * Retrieve the date categories from the energy usage list.
  *
  * @param energyUsages Energy usage details
  */
  def getCategories(energyUsages: List[EnergyUsage]) = {
    for (e <- energyUsages) yield Json.parse(sdf.format(e.effectiveFrom))
  }

 /**
  * Retrieve the usage date from the energy usage list.
  *
  * @param energyUsages Energy usage details
  */
  def getUsageData(energyUsages: List[EnergyUsage]) = {
    for (e <- energyUsages) yield Json.parse(e.usage.toString)
  }

 /**
  * Retrieve the cost data from the energy usage list.
  *
  * @param energyUsages Energy usage details
  */
  def getCostData(energyUsages: List[EnergyUsage]) = {
    for (e <- energyUsages) yield Json.parse("%.2f".format((e.cost * e.usage)))
  }

 /**
  * Get commodity label from commodity code.
  *
  * @param commodity Commodity code (E or G)
  */
  def getCommodityLabel(commodity: String) = {
    commodity match {
      case "E" => "Electricity"
      case "G" => "Gas"
      case _ => "Unknown"
    }
  }

 /**
  * Action to fetch energy usage data for a customer.
  *
  * @param id Customer ID
  * @param commodity Commodity code (default "E")
  */
  def fetch(id: Long, commodity: String="E") = DBAction { implicit rs =>
    Logger.debug(f"fetching chart data for customer id:[${id}%d] and commodity:[${commodity}%s]")
    
    val energyUsages = EnergyUsageDAO.findAllByCustomerIdAndCommodity(id, commodity)

    Logger.debug(f"energyUsages size:[${energyUsages.size}%d]")
    
    val json: JsValue = Json.obj(
        "categories" -> JsArray(getCategories(energyUsages)),
        "series" -> Json.arr(
          Json.obj(
            "name" -> getCommodityLabel(commodity),
            "data" -> JsArray(getUsageData(energyUsages))
          ),
          Json.obj(
            "name" -> "Cost",
            "data" -> JsArray(getCostData(energyUsages))
          )
        )
      )

    Ok(json)
    
  }

  
}